/*
   Copyright 2009 Marcin Szczepanski, webqem (marcins@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

/*
 * This function will be called by the AS3 Wave API to setup the callbacks.
 */
 
var _gadgetName = ""; 
function initialiseFlash(gadgetName) 
	{
	_gadgetName = gadgetName;
    if(wave && wave.isInWaveContainer()) {
    //alert("Initialising for " + gadgetName);
	    
	// doing it via a closure seemed to be more reliable than
	// directly setting the callback to the Flash function
	wave.setStateCallback( function() { 
	    document.getElementById(gadgetName).waveStateCallback(); 
	});
	
	wave.setParticipantCallback( function() { 
	    document.getElementById(gadgetName).waveParticipantCallback(); 
	});
	
	wave.setModeCallback(waveModeCallback, this);
	
    }
}   

function waveModeCallback(mode)
{
	var flashMode = "unknown";
	switch(mode) {
	case wave.Mode.PLAYBACK:
		flashMode = "playback";
		break;
	case wave.Mode.EDIT:
		flashMode = "edit";
		break;
	case wave.Mode.VIEW:
		flashMode = "view";
		break;
	}
	document.getElementById(_gadgetName).waveModeCallback(flashMode);
}

/* Flex/JS BRIDGE FUNCTIONS */

function waveIsInWave()
{
    return (wave && wave.isInWaveContainer());
}

/* State */     
function waveStateGet(key, defaultValue)
{
    return wave.getState().get(key, defaultValue);
}

function waveStateGetKeys()
{
    return wave.getState().getKeys();
}

/*
* Flash doesn't properly auto coerce an AS Object to a Javascript 
* object, so instead the AS explodes the object into separate key and 
* value arrays and sends those.  That just means this function needs to 
* rebuild the delta object before calling the Wave API
*/
function waveStateSubmitDelta(keys,values)
{
    var length = keys.length;
    var delta = {};
    for(var i = 0; i < length; i++) {
        delta[keys[i]] = values[i];
    }
    wave.getState().submitDelta(delta);
}

function waveStateToString()
{
    return wave.getState().toString();
}

/* Participant */
function waveParticipantGetViewer()
{
    return wave.getViewer().getId();
} 

function waveParticipantGetHost()
{
    return wave.getHost().getId();
}

function waveParticipantGetAll()
{
    return wave.getParticipants();
}

function waveParticipantDisplayName(id)
{
    return wave.getParticipantById(id).getDisplayName();
}

function waveParticipantThumbnailUrl(id)
{
    return wave.getParticipantById(id).getThumbnailUrl();
}